<?php declare(strict_types=1);

namespace Reezy\OAuth;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Reezy\OAuth\Contract\OAuthManagerInterface;

class OAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var OAuthManagerInterface
     */
    protected $oauthManager;

    /**
     * OAuthMiddleware constructor.
     * @param OAuthManagerInterface $oauthLogin
     */
    public function __construct(OAuthManagerInterface $oauthLogin)
    {
        $this->oauthManager = $oauthLogin;
    }


    /**
     * Process an incoming server request.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $userId = $this->oauthManager->oauth($request);
        } catch (OAuthRedirectException $exception) {
            return $exception->getResponse();
        }

        return $handler->handle($request->withAttribute('userId', $userId));
    }

}
